<?php
namespace app\admin\controller;

use app\common\controller\Backend;
use think\Cache;
use think\Db;
use think\Session;
use \app\admin\model\RegistrActivity as RegistrActivitys;

/**
 * 歷史登記列管理
 *
 * @icon fa fa-circle-o
 */
class RegistrActivityUser extends Backend
{

    /**
     * RegistrActivityUser模型对象
     * @var \app\admin\model\RegistrActivityUser
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\RegistrActivityUser;
        $contentList = Db::name('activity_register__category')->where('deletetime', null)->order('weigh desc')->select();

        $this->view->assign("contentList", $contentList);
        $this->view->assign("sexList", $this->model->getSexList());
        $this->view->assign("eduList", $this->model->getEducationList());
        $this->view->assign("voterList", $this->model->getIsVoterList());
        $this->view->assign("cognitiveList", $this->model->getCognitiveApproachList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index($ids = null)
    {
        $this->assignconfig("activity_id", $ids);
        Cache::set('activity_id_user', $ids, 864000);

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['registractivity', 'user', 'consultationcategory'])
                ->where($where)
                ->where(['registr_activity_id' => $ids])
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $start = mb_substr($row['id_card'], 0, -1);
                $last  = mb_substr($row['id_card'], -1, 1);
                //$row['id_card']='('.$row['id_card'].')';
                $row['id_card'] = $start . '(' . $last . ')';

                $row->getRelation('registractivity')->visible(['name']);
                $row->getRelation('user')->visible(['nickname']);
            }

            $result = ["total" => $list->total(), "rows" => $list->items()];

            return json($result);
        }

        $this->assignconfig("registr_activity_user_edit", $this->auth->check("registr_activity_user/edit"));
        $this->assignconfig("registr_activity_user_del", $this->auth->check("registr_activity_user/del"));

        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (! $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk       = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();

                }
                $params['registr_activity_id'] = Cache::get('activity_id_user');
                //签到人数
                $model2 = new RegistrActivitys;
                $model2->where(['id' => $params['registr_activity_id']])->setDec('join_nun');

                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    /**
     * 新增
     */
    public function add($id=null)
    {

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (! in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $params['native_place'] = '';
                    if (isset($params['province'])) {
                        $province = Db::name('region')->where('id', $params['province'])->value('name');

                        $params['native_place'] = $province;
                    }

                    if (isset($params['city'])) {
                        $city = Db::name('region')->where('id', $params['city'])->value('name');

                        $params['native_place'] .= $city;
                    }
                    if (isset($params['district'])) {
                        $district = Db::name('region')->where('id', $params['district'])->value('name');

                        $params['native_place'] .= $district;
                    }

                  

                    $params['registr_activity_id'] =$id;
                    $params['source']              = 1;
                    $result                        = $this->model->allowField(true)->save($params);

                    //签到人数
                    $model2 = new RegistrActivitys;
                    $model2->where(['id' => $params['registr_activity_id']])->setInc('join_nun');

                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (! $row) {
            $this->error(__('No Results were found'));
        }
        $user             = db('user')->where(['id' => $row['user_id']])->find();
        $registr_activity = db('registr_activity')->where(['id' => $row['registr_activity_id']])->find();

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (! in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        $this->view->assign("user", $user);
        $this->view->assign("registr_activity", $registr_activity);
        return $this->view->fetch();
    }

    public function user_list($ids)
    {
        $this->assignconfig("ids", $ids);
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $obj                                         = $this->model->where($where);
            $admin                                       = Session::get('admin');
            if ($admin['affiliated_center_id'] != 0) {
                $arr_area = explode(',', $admin['affiliated_center_id']);
                $obj->where(['a.area_one_id' => ['in', $arr_area]]);
            }

            $list = $obj
                ->alias('d')
                ->field('a.name as activity_name,d.createtime,d.name,d.id_card,d.consultation_content,d.hk_mobile,d.nd_mobile,d.hk_address,d.nd_address')
                ->join('registr_activity a', 'a.id = d.registr_activity_id', 'left')
                ->where('d.user_id', '=', $ids)
                ->order('d.id desc')
                ->paginate($limit);

            foreach ($list as $key => $row) {
                $start = substr($row['id_card'], 0, -1);
                $last  = substr($row['id_card'], -1, 1);

                $row['id_card'] = $start . '(' . $last . ')';
            }

            $result = ["total" => $list->total(), "rows" => $list->items()];

            return json($result);
        }

        return $this->view->fetch();
    }

}
